package com.itgo.codegen.gen;

import java.util.List;

import com.itgo.codegen.bean.ColumnMeta;
import com.itgo.codegen.bean.MapperTemplateBean;
import com.itgo.codegen.bean.TableMeta;
import com.itgo.codegen.config.Config;
import com.itgo.codegen.util.StringLang;

public class MapperGen extends AbstractGen{
	private TableMeta tableMeta ;
	public MapperGen( TableMeta tableMeta ){
		if( tableMeta == null ){
			throw new IllegalArgumentException("table meta is not empty .") ;
		}
		this.tableMeta = tableMeta ;
	}
	
	@Override
	protected MapperTemplateBean build() {
		MapperTemplateBean template = new MapperTemplateBean(
				buildBaseColumn ( ) , buildInertFields ()  , buildInsertValues () , buildUpdateSets() ) ;
		return template;
	}
	
	private String buildBaseColumn(){
		StringBuilder sbuff = new StringBuilder() ;
		List<ColumnMeta> columnMetas = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columnMetas ){
			sbuff.append( tableMeta.getTableAliasName()+"."+column.getColumnName() ) ;
			sbuff.append(" , ") ;
		}
		return StringLang.trim( sbuff.toString() , null , ",") ;
	}
	
	private String buildInertFields(){
		StringBuilder sbuff = new StringBuilder() ;
		List<ColumnMeta> columnMetas = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columnMetas ){
			if( column.isPk() ){
				continue ;
			}
			String fieldName = StringLang.tfRule( column.getColumnName() ) ;
			sbuff.append(String.format(
							"\r\n\t\t\t<if test=\"%s != null\">\r\n\t\t\t\t%s , \r\n \t\t\t</if>", fieldName , column.getColumnName()  ) ) ;
			
		}
		return sbuff.toString() ;
	}
	
	private String buildInsertValues(){
		StringBuilder sbuff = new StringBuilder() ;
		List<ColumnMeta> columnMetas = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columnMetas ){
			if( column.isPk() ){
				continue ;
			}
			String fieldName = StringLang.tfRule( column.getColumnName() ) ;
			System.out.println(column.getDataType());
			String jdbcType = Config.TypeEnum.byDBType( column.getDataType() ).getJdbcType() ;
			sbuff.append(
					String.format( "\r\n\t\t\t<if test=\"%s != null\">\r\n\t\t\t\t#{%s,jdbcType=%s} , \r\n \t\t\t</if>", 
							fieldName ,fieldName, jdbcType ) ) ;
			
		}
		return sbuff.toString() ;
	}
	
	private String buildUpdateSets(){
		StringBuilder sbuff = new StringBuilder() ;
		List<ColumnMeta> columnMetas = tableMeta.getColumnMetas() ;
		for( ColumnMeta column : columnMetas ){
			if( column.isPk() ){
				continue ;
			}
			String fieldName = StringLang.tfRule( column.getColumnName() ) ;
			String jdbcType = Config.TypeEnum.byDBType( column.getDataType() ).getJdbcType() ;
			sbuff.append(
					String.format( "\r\n\t\t\t\t<if test=\"%s != null\">\r\n \t\t\t\t\t%s = #{%s,jdbcType=%s} , \r\n \t\t\t\t</if>", 
							fieldName , column.getColumnName() , fieldName , jdbcType ) ) ;
			
		}
		return sbuff.toString() ;
	}
	
}
